<template>
  <div>
    <el-form label-width="100px" :model="skuInfo">
      <el-form-item label="SPU名称"> {{ spu.spuName }} </el-form-item>

      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
      </el-form-item>

      <el-form-item label="价格(元)">
        <el-input
          placeholder="价格(元)"
          type="number"
          v-model="skuInfo.price"
        ></el-input>
      </el-form-item>

      <el-form-item label="重量(千克)">
        <el-input
          placeholder="重量(千克)"
          type="number"
          v-model="skuInfo.weight"
        ></el-input>
      </el-form-item>

      <el-form-item label="规格描述">
        <el-input
          type="textarea"
          placeholder="规格描述"
          v-model="skuInfo.skuDesc"
        ></el-input>
      </el-form-item>

      <el-form-item label="平台属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item
            :label="attr.attrName"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <el-select placeholder="请选择" v-model="attr.attrIdValueId">
              <el-option
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
                v-for="(attrValue, index) in attr.attrValueList"
                :key="attrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item
            :label="saleAttr.saleAttrName"
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
          >
            <el-select
              placeholder="请选择"
              v-model="saleAttr.saleAttrIdValueId"
            >
              <el-option
                :label="saleAttrValue.saleAttrValueName"
                :value="`${saleAttr.id}:${saleAttrValue.id}`"
                v-for="(saleAttrValue, index) in saleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="图片列表">
        <el-table
          style="width: 100%"
          border
          :data="spuImageList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="图片" width="width">
            <template slot-scope="{ row, $index }">
              <img
                :src="row.imgUrl"
                alt=""
                style="width: 100px; height: 100px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button
                @click="changeDefault(spuImageList, row)"
                type="primary"
                size="mini"
                v-if="row.isDefault === '0'"
                >设为默认</el-button
              >
              <el-tag type="success" size="mini" v-else>默认</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancelBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import { sku } from "@/api/product";
export default {
  name: "SkuForm",
  data() {
    return {
      spu: {},
      attrList: [],
      spuImageList: [],
      spuSaleAttrList: [],
      skuImageList: [],
      skuInfo: {
        // 父组件传递过来的
        category3Id: "",
        spuId: "",
        tmId: "",

        // 通过v-model直接收集的
        skuName: "",
        skuDesc: "",
        weight: "",
        price: "",

        // 通过js代码收集
        skuDefaultImg: "",
        skuAttrValueList: [
          // {
          //   attrId: 0,
          //   valueId: 0,
          // }
        ],
        skuSaleAttrValueList: [
          // {
          //   saleAttrId: 0,
          //   saleAttrValueId: 0,
          // }
        ],
        skuImageList: [
          // {
          //   imgName: "string",
          //   imgUrl: "string",
          //   isDefault: "string",
          //   spuImgId: 0
          // }
        ],
      },
    };
  },
  methods: {
    //初始化数据渲染
    async getInitAddSkuFormData(spu, category1Id, category2Id) {
      this.spu = spu;
      // http://localhost:9528/dev-api/admin/product/spuSaleAttrList/1539
      // 获取指定SPU的id对应的销售属性列表
      const promise1 = this.$API.sku.getSpuSaleAttrList(spu.id);
      // http://localhost:9528/dev-api/admin/product/attrInfoList/2/13/61
      // 获取商品属性列表
      const promise2 = this.$API.attr.getList(
        category1Id,
        category2Id,
        spu.category3Id
      );

      //  http://localhost:9528/dev-api/admin/product/spuImageList/1539
      // 获取指定SPU的id对应的图片列表
      const promise3 = this.$API.sku.getSpuImageList(spu.id);

      try {
        const result = await Promise.all([promise1, promise2, promise3]);
        this.spuSaleAttrList = result[0].data;
        this.attrList = result[1].data;
        // this.spuImageList = result[2].data;
        let spuImageList = result[2].data;
        spuImageList.forEach((item) => (item.isDefault = "0"));
        this.spuImageList = spuImageList;
      } catch (error) {
        this.$message.error("请求获取初始化数据失败", error.message);
      }
    },

    //选择图片的回调
    handleSelectionChange(val) {
      console.log(val);
      this.skuImageList = val;
    },
    //排他设为默认
    changeDefault(spuImageList, row) {
      spuImageList.forEach((item) => {
        item.isDefault = "0";
      });
      row.isDefault = "1";
      //收集默认图片的路径
      this.skuInfo.skuDefaultImg = row.imgUrl;
    },
    //保存操作
    async save() {
      // 收集数据
      let { spu, attrList, spuSaleAttrList, skuInfo, skuImageList } = this;
      //整理数据
      //  整理 spu
      skuInfo.category3Id = spu.category3Id;
      skuInfo.spuId = spu.id;
      skuInfo.tmId = spu.tmId;
      //整理skuAttrValueList
      skuInfo.skuAttrValueList = attrList.reduce((prev, item) => {
        if (item.attrIdValueId) {
          let [attrId, valueId] = item.attrIdValueId.split(":");
          let obj = {
            attrId,
            valueId,
          };
          prev.push(obj);
        }

        return prev;
      }, []);
      //整理skuSaleAttrValueList
      skuInfo.skuSaleAttrValueList = spuSaleAttrList.reduce((prev, item) => {
        if (item.saleAttrIdValueId) {
          let [saleAttrId, saleAttrValueId] = item.saleAttrIdValueId.split(":");
          let obj = {
            saleAttrId,
            saleAttrValueId,
          };
          prev.push(obj);
        }
        return prev;
      }, []);

      //整理skuImageList
      skuInfo.skuImageList = skuImageList.map((item) => ({
        imgName: item.imgName,
        imgUrl: item.imgUrl,
        isDefault: item.isDefault,
        spuImgId: item.id,
      }));
      //发请求
      try {
        const result = await this.$API.sku.addUpdate(skuInfo);
        if (result.code === 20000 || result.code === 200) {
          this.$message.success("保存sku成功");
          this.$emit("update:isShowSkuForm", false);
          this.resData();
        } else {
          this.$message.error("保存sku失败");
        }
      } catch (error) {
        this.$message.error("请求保存sku失败");
      }
    },
    //重置sku
    resData() {
      Object.assign(this._data, this.$options.data());
    },
    //取消后重置sku
    cancelBack() {
      this.$emit("update:isShowSkuForm", false);
      this.resData();
    },
  },
};
</script>

<style>
</style>